<template>
  <div class="user-profile">
    <div class="page-header">
      <h1>个人信息</h1>
      <p>查看和编辑您的个人信息</p>
    </div>

    <el-card v-loading="loading">
      <el-form 
        :model="userForm" 
        :rules="formRules"
        ref="formRef"
        label-width="100px" 
        class="profile-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="userForm.gender">
            <el-radio value="0">未知</el-radio>
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="updateProfile" :loading="updating">更新信息</el-button>
          <el-button @click="showPasswordDialog">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePassword" :loading="updatingPassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const updating = ref(false)
const updatingPassword = ref(false)
const passwordDialogVisible = ref(false)

// 用户信息表单
const userForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  gender: '0'
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const formRef = ref()
const passwordFormRef = ref()

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码修改验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载用户信息
const loadUserProfile = async () => {
  try {
    loading.value = true
    const response = await request.get('/api/users/profile')
    
    if (response.data.code === 200) {
      const userData = response.data.data
      Object.assign(userForm, {
        username: userData.username,
        realName: userData.realName || '',
        email: userData.email || '',
        phone: userData.phone || '',
        gender: userData.gender ? userData.gender.toString() : '0'
      })
    } else {
      ElMessage.error(response.data.message || '加载用户信息失败')
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  } finally {
    loading.value = false
  }
}

// 更新个人信息
const updateProfile = async () => {
  try {
    await formRef.value.validate()
    
    updating.value = true
    const response = await request.put('/api/users/profile', {
      realName: userForm.realName,
      email: userForm.email,
      phone: userForm.phone,
      gender: parseInt(userForm.gender)
    })
    
    if (response.data.code === 200) {
      ElMessage.success('个人信息更新成功')
      // 更新存储中的用户信息
      authStore.updateUserInfo({
        realName: userForm.realName,
        email: userForm.email,
        phone: userForm.phone,
        gender: parseInt(userForm.gender)
      })
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    if (error !== false) { // 不是验证错误
      console.error('更新个人信息失败:', error)
      ElMessage.error('更新个人信息失败')
    }
  } finally {
    updating.value = false
  }
}

// 显示修改密码对话框
const showPasswordDialog = () => {
  passwordDialogVisible.value = true
  // 重置表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

// 修改密码
const updatePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    updatingPassword.value = true
    const response = await request.put('/api/users/password', {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response.data.code === 200) {
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(response.data.message || '密码修改失败')
    }
  } catch (error) {
    if (error !== false) { // 不是验证错误
      console.error('密码修改失败:', error)
      ElMessage.error('密码修改失败')
    }
  } finally {
    updatingPassword.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.profile-form {
  max-width: 600px;
}
</style> 